#!/usr/bin/env python

import sys, os, shutil, re

def define(config, what):
  opp_config = open(config, "r+")
  lines = opp_config.readlines()
  opp_config.seek(0)
  opp_config.close()
  i = 0
  for line in lines:
    if re.search(what, line):
      lines[i] = "#define " + what + "\n"
      break
    i = i + 1
  opp_config = open(config, "w")
  opp_config.writelines(lines)
  opp_config.close()

def undefine(config, what):
  opp_config = open(config, "r+")
  lines = opp_config.readlines()
  opp_config.seek(0)
  opp_config.close()
  i = 0
  for line in lines:
    if re.search(what, line):
      lines[i] = "#undef " + what + "\n"
      break
    i = i + 1
  opp_config = open(config, "w")
  opp_config.writelines(lines)
  opp_config.close()

# Configuration section
string_base = os.path.realpath(__file__)
string_base = string_base[:-11]
string_base += "bin/"
string_list = ["G30000", "G80000", "G150000", "G1600000", "G10000000"]

config_file_name = string_base[:-9] + "include/config.h"
undefine(config_file_name, "DEBUG")
undefine(config_file_name, "TEST")
undefine(config_file_name, "CHRONO")


# Compare trees with bison
print "tester> checking AST against Bison"
define(config_file_name, "SERIALIZE")

os.chdir("..")
if os.system("./generator.py test/left_rec_grammar > /dev/null") != 0:
  print "tester> no left-recursive grammar present, please make sure a left-recursive grammar is available in left_rec_grammar"
  sys.exit(-1)
if os.system("make clean > /dev/null && make > /dev/null") != 0:
  print "tester> could not compile libopp\n"
  sys.exit(-1)
print "tester> compiled libopp"
os.chdir("tools/checker")
if os.system("make clean > /dev/null && make > /dev/null") != 0:
  print "tester> could not compile checker\n"
  sys.exit(-1)
print "tester> compiled checker"
for string in string_list:
  print "tester> checking string %s" % string
  if os.system("./checker %s" % (string_base + string)) != 0:
    print "tester> string %s: \33[1;31mfailure\33[0m, ASTs are different" % string
    sys.exit(0)
  print "tester> string %s: \33[1;32msuccess\33[0m, ASTs are equal" % string
os.chdir("../..")
if os.system("./generator.py test/right_rec_grammar > /dev/null") != 0:
  print "tester> no right-recursive grammar present, please make sure a right-recursive grammar is available in right_rec_grammar"
  sys.exit(-1)

print "tester> \33[1;32mSUCCESS\33[0m"

undefine(config_file_name, "SERIALIZE")

